#include "User.h"
#include "ThreadDS.h"

void User::setFd(SOCKET fd) {
	this->close();
	this->fd = fd;
	++fdcnt;
	opened = true;
	if(!msgs.empty()) {
		sendmsg(msgs.front());
		msgs.pop();
		close();
	} else {
		regHandle(new ThreadDS(comet, this));
	}
}

void User::close() {
	if(!opened) return ;
#ifdef WIN32
	closesocket(fd);
#else
	::close(fd);
#endif

	opened = false;
}
void User::sendmsg(const std::string& msg) {
	if(send(fd, msg.c_str(), msg.length(), 0) == -1) {
		std::cerr << "send msg error in " << __FILE__ << std::endl;
	}
}
void User::addmsg(const std::string& msg) {
	std::cout << "try to send msg, fd is " << opened << std::endl;
	msgs.push(msg);

	if(opened && !msgs.empty()) {
		sendmsg(msgs.front());
		msgs.pop();
		close();
	}
	//if(opened) {
	//	sendmsg(msg);
	//	close();
	//} else {
	//	msgs.push(msg);
	//}
}

